{% extends 'index.html' %}
{% load my_tag my_filter %}
{% block css %}
    <link rel="stylesheet" href="/static/viewer/css/viewer.css">
    <link rel="stylesheet" href="/static/editor-md/css/editormd.css"/>
    <link rel="stylesheet" href="/static/my/css/article.css">
{% endblock %}

{% block banner %}
    {% banner 'article' article_obj %}
{% endblock %}

{% block main %}
    <div class="slide_or_actions" ref="slider">
        <div class="slider_bar">
            <div class="title">
                <span>[[ slide_text ]]</span>
                <el-switch
                        v-model="isShowSlider"
                        active-color="#13ce66"
                        inactive-color="#9e9e9e"
                        @change="sliderChange"
                >
                </el-switch>
            </div>
            <div class="body">
                <el-scrollbar id="el_scrollbar">
                    <p :tagName="item.tagName" @click="go_side_bar(item.pos, $event)"
                       v-for="(item, index) in slide_list"
                       :key="index">
                        [[ item.c ]]
                    </p>
                </el-scrollbar>
            </div>
        </div>

        <div class="article_actions">
            <div class="item" title="文章点赞">
                <i class="fas fa-thumbs-up" @click="article_digg($event, '{{ article_obj.nid }}')"></i>
                <span>{{ article_obj.digg_count }}</span>
            </div>
            <div class="item" title="文章收藏">
                <i class="fas fa-star {{ article_obj|is_user_collects:request }}"
                   @click="article_collects($event, '{{ article_obj.nid }}')"></i>
                <span>{{ article_obj.collects_count }}</span>
            </div>
            <div class="item" title="回到顶部">
                <i class="fa fa-angle-double-up" @click="go_to_top"></i>
            </div>
        </div>

    </div>
    <div class="article">
        <div class="article_title">
            <h2>{{ article_obj.title }}
                {% if request.user.is_superuser %}
                    <a href="/backend/edit_article/{{ article_obj.nid }}/"><i class="fas fa-edit"></i></a>
                {% endif %}
            </h2>
            <p>
                <span>发布时间：<i>{{ article_obj.create_date|date:'Y-m-d' }}</i></span>
                <span>作者：<i>{{ article_obj.author }}</i></span>
                <span>来源：<i>{{ article_obj.source }}</i></span>
            </p>

            <div>
                {% if article_obj.tag.all %}
                    <i title="文章标签" class="fas fa-tags"></i>
                    {% for tag in article_obj.tag.all %}
                        <i>{{ tag.title }}</i>
                    {% endfor %}
                {% endif %}
            </div>


        </div>
        <div class="article_content" id="article_content" v-pre>
            <textarea style="display:none;">{{ article_obj.content }}</textarea>
        </div>
        <div class="article_bottom">
            <div class="item" title="文章点赞">
                <i class="fas fa-thumbs-up" @click="article_digg($event, '{{ article_obj.nid }}')"></i>
                <span>{{ article_obj.digg_count }}</span>

            </div>
            <div class="item" title="文章收藏">
                <i class="fas fa-star {{ article_obj|is_user_collects:request }}"
                   @click="article_collects($event, '{{ article_obj.nid }}')"></i>
                <span>{{ article_obj.collects_count }}</span>
            </div>
            <div class="item" title="回到顶部">
                <i class="fa fa-angle-double-up" @click="go_to_top"></i>
            </div>
        </div>
        {% block prev_next %}
            <div class="prev_next_article">
                <div class="pn_content">
                    {% generate_p_n article_obj %}
                </div>
            </div>
        {% endblock %}

        <div class="comment_submit">
            <div class="title">
                你觉得文章怎么样
            </div>
            {% csrf_token %}
            <div class="body">
                <textarea
                        @keydown.enter.ctrl="add_comment({{ article_obj.nid }})"
                        ref="comment_content" rows="10"
                        v-model="comment_content"
                        class="add_comment"
                        placeholder="写下你想说的话，开始我们的对话 (支持markdown语法)"></textarea>
                <i class="face_icon">
                    <img src="/static/emoji/img.png" style="width: 25px; height: 25px; cursor: pointer" alt="">
                </i>
                <button class="submit_comment" @click="add_comment({{ article_obj.nid }})">
                    发布评论
                </button>
            </div>
            <div class="footer">
                <p><span>{{ article_obj.look_count }}</span> 人参与，<span>{{ article_obj.comment_count }}</span> 条评论</p>
            </div>
        </div>
        <div class="comment_list" comment_list="{{ comment_list|get_coll_nid }}">
            <ul>
                {% for comment in comment_list %}
                    <li>
                        <div class="left">
                            <img src="{{ comment.user|get_avatar }}"
                                 alt="">
                        </div>
                        <div class="right">
                            <h4>{{ comment.user.nick_name }}</h4>
                            <div id="comment_show__{{ comment.nid }}">
                                <textarea style="display:none;">{{ comment.content }}</textarea>
                            </div>
                            <div class="comment_info">
                                <span>{{ comment.create_time|date_humaniz }}</span>
                                <div>
                                    <span @click="comment_digg($event, '{{ comment.nid }}')">点赞（{{ comment.digg_count }}）</span>
                                    <span @click="show_sub_comment_list($event, '{{ comment.user.nick_name }}', '{{ comment.nid }}')">回复（{{ comment.comment_count }}）</span>
                                    {% if comment.user == request.user or request.user.is_superuser %}
                                        <span class="delete"
                                              @click="delete_sub_comment('{{ comment.nid }}', '{{ article_obj.nid }}', null)">
                                        删除
                                    </span>
                                    {% endif %}

                                </div>
                            </div>

                            <div class="sub_comment_list">
                                {% for sub in comment.sub_comment %}
                                    <div class="sub_comment_item">
                                        <div class="left">
                                            <img src="{{ sub.user|get_avatar }}"
                                                 alt="">
                                        </div>
                                        <div class="right">
                                            <h4>{{ sub.user.nick_name }} @ {{ sub.parent_comment.user.nick_name }}</h4>
                                            <div class="sub_comment_content">
                                                {{ sub.content }}
                                            </div>
                                            <div class="sub_comment_info">
                                                <span>{{ sub.create_time|date_humaniz }}</span>
                                                <div>
                                                    <span @click="comment_digg($event, '{{ sub.nid }}')">点赞（{{ sub.digg_count }}）</span>
                                                    <span @click="sub_comment_set_placeholder($event, '{{ sub.user.nick_name }}', '{{ sub.nid }}')">回复</span>
                                                    {% if sub.user == request.user or request.user.is_superuser %}
                                                        <span class="delete"
                                                              @click="delete_sub_comment('{{ sub.nid }}', '{{ article_obj.nid }}', '{{ comment.nid }}')">删除</span>
                                                    {% endif %}

                                                </div>
                                            </div>
                                        </div>

                                    </div>
                                {% endfor %}

                                <div class="sub_comment_textarea">
                                    <textarea name="" id="" cols="30" ref="sub_comment_content" rows="10"
                                              placeholder="@fengfeng"></textarea>
                                    <button @click="add_sub_comment($event, '{{ article_obj.nid }}')">回复</button>
                                </div>
                            </div>
                        </div>
                    </li>
                {% endfor %}
            </ul>
        </div>
    </div>
{% endblock %}


             <div class="my_card">
                            <div class="title">
                                <h3>个人名片</h3>
                                <h4>MY</h4>
                                <h4>PROFILE</h4>
                                <img src="/static/my/img/footer/weichat.png" alt="我的微信">
                            </div>
                            <div class="jieqi">
                                <img id="jieqiset" src="http://cdn.qiniu.daoyuanyi.com/blog/24_hourse/20.png" alt="24节气">
                            </div>
                            <div class="footer">
                                <p>NAME <span>{{ SITE_INFO.name }}</span></p>
                                <p>JOB <span>{{ SITE_INFO.job }}</span></p>
                                <p>ADDR <span>{{ SITE_INFO.address }}</span></p>
                                <p>WEB <a target="_blank"
                                          href="//{{ SITE_INFO.link }}">{{ SITE_INFO.link }}</a>
                                </p>
                            </div>
                        </div>

{% block article_js %}
    <script src="/static/editor-md/lib/marked.min.js"></script>
    <script src="/static/editor-md/lib/prettify.min.js"></script>
    <script src="/static/jquery/jquery.min.js"></script>
    <script src="/static/editor-md/editormd.min.js"></script>
    <script src="/static/viewer/js/viewer.js"></script>
    <script src="/static/emoji/sina.js"></script>
    <script type="text/javascript">

        $(function () {
            let editor = editormd.markdownToHTML("article_content", {
                width: "100%",
                height: "100%",
                path: "/static/editor-md/lib/",
                htmlDecode: true,
                codeFold: true,
            });

            let comment_list = document.querySelector('.comment_list')
            let lis = eval(comment_list.getAttribute('comment_list'))

            for (const li of lis) {
                editormd.markdownToHTML(`comment_show__${li}`, {
                    width: "100%",
                    height: "100%",
                    path: "/static/editor-md/lib/",
                });
            }


            $('#article_content').viewer();
            // 绑定表情
            $('.face_icon').SinaEmotion($('.add_comment'), vue, 'comment_content');
            $('.comment_list .editormd-html-preview').viewer();


        });
    </script>
{% endblock %}


<style>
    @import "../../emoji/face.css";
    @import "editormd/code.css";

    main {
        position: relative;
        justify-content: initial;
    }

    .article {
        width: calc(100% - 200px);
        position: relative;
        transition: all 0.3s;

    .article_title {
        border-radius: 5px 5px 0 0;
        display: flex;
        flex-direction: column;
        align-items: center;
        background-color: var(--card_bg);

    h2 {
        margin: 10px 0;
    }

    p {
        font-size: 14px;
        color: var(--font_1);

    span {
        margin-right: 10px;

    &
    :last-child {
        margin-right: 0;
    }

    }
    }

    > div {
        margin: 10px 0;

    i {
        font-size: 14px;
        margin-right: 5px;
        color: var(--active);

    &
    :first-child {
        color: var(--font_1);
    }

    }
    }
    }

    .article_content {
        margin-top: 1px;
        min-height: 200px;
        background-color: var(--card_bg);
        width: 100%;

    ol, li, ul {
        list-style: inherit;
    }

    }

    .article_bottom {

        display: none;
    }

    .prev_next_article {
        background-color: var(--card_bg);
        padding: 20px;
        border-radius: 0 0 5px 5px;

    .pn_content {
        border-top: 1px solid var(--bg);
        width: 100%;
        display: flex;
        padding-top: 5px;
        justify-content: space-between;

    a {
        color: var(--font_1);
    }

    }
    }

    .comment_submit {
        margin-top: 20px;
        min-height: 200px;
        background-color: var(--card_bg);
        padding: 20px 20px 10px 20px;

    .title {
        padding-bottom: 10px;
        margin-bottom: 10px;
        border-bottom: 1px solid var(--bg_darken);
        color: var(--font_1);
        position: relative;

    &
    ::after {
        display: block;
        content: '';
        width: 145px;
        height: 1px;
        background-color: var(--bg);
        position: absolute;
        bottom: 0;
        left: 0;
    }

    }

    .body {
        width: 100%;
        padding: 20px;
        height: 150px;
        background-color: var(--ele_bg);
        border-radius: 5px;
        position: relative;
        box-shadow: inset 2px 2px 6px rgb(0 0 0 / 8%);

    textarea {
        width: 100%;
        height: 100%;
        background-color: transparent;
        border: none;
        resize: none;
        color: var(--font_2);

    &
    :focus {
        border: none;
        outline: none;
    }

    }

    .face_icon {
        position: absolute;
        left: 15px;
        bottom: 10px;
    }

    > button {
        width: 100px;
        height: 40px;
        border-radius: 10px;
        background-color: var(--active);
        color: white;
        border: none;
        cursor: pointer;

        position: absolute;
        bottom: 20px;
        right: 20px;
    }

    }

    .footer {
        font-size: 14px;
        color: #555555;
        margin-top: 10px;

    p > span {
        color: #ff9800;
    }

    }
    }

    .comment_list {
        margin-top: 20px;

    ul {
        list-style: none;
    }

    > ul {

    > li {
        width: 100%;
        display: flex;
        margin-bottom: 20px;

    > .left {
        width: 70px;

    img {
        width: 50px;
        border-radius: 5px;
        transition: all 0.3s;

    &
    :hover {
        transform: scale(1.1);
    }

    }
    }

    > .right {
        width: calc(100% - 70px);
        background-color: var(--card_bg);
        border-radius: 5px;
        position: relative;
        box-shadow: 1px 1px 5px rgba(0, 0, 0, 0.1);
        padding: 10px 20px;

    &
    ::after {
        display: block;
        content: '';
        position: absolute;
        left: -20px;
        top: 15px;
        width: 0;
        height: 0;
        border: 10px solid transparent;
        border-right-color: var(--card_bg);
    }

    .comment_content {
        margin: 5px 0;

    img {
        margin-top: 5px;
        height: 120px;
        margin-right: 10px;
        border-radius: 5px;
        box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
    }

    img[alt="emoji"] {
        width: 22px;
        height: 22px;
        box-shadow: none;
    }

    }

    .comment_info {
        display: flex;
        justify-content: space-between;
        font-size: 14px;

    > div > span {
        cursor: pointer;
    }


    }

    .delete {
        color: var(--font_del);
        cursor: pointer;
    }

    .sub_comment_list {
        margin-top: 10px;
        display: none;

    > div {
        display: flex;
        margin-bottom: 10px;

    .left {
        width: 60px;

    img {
        width: 40px;
        border-radius: 5px;

        transition: all 0.3s;

    &
    :hover {
        transform: scale(1.1);
    }

    }
    }

    .right {
        width: calc(100% - 60px);

    .sub_comment_content {
        margin: 5px 0;
    }

    .sub_comment_info {
        display: flex;
        justify-content: space-between;
        font-size: 14px;

    > div > span {
        cursor: pointer;
    }

    }
    }
    }

    .sub_comment_textarea {
        position: relative;

        width: 100%;
        margin-bottom: 10px;

    > textarea {
        resize: none;
        width: 100%;
        padding: 10px;
        border: 1px solid var(--bg_darken);
        border-radius: 5px;
        color: var(--font_2);
        background-color: var(--bg);

    &
    :focus {
        border: none;
        outline: none;
    }

    }

    button {
        position: absolute;
        right: 20px;
        bottom: 20px;

        width: 80px;
        height: 30px;
        border-radius: 5px;
        background-color: var(--active);
        color: white;
        border: none;
        cursor: pointer;
    }

    }
    }
    }
    }
    }

    .editormd-html-preview {
        padding: 10px 0;

    p {
        display: flex;
        flex-wrap: wrap;
        align-items: center;
    }

    p > img {
        height: 100px;
        border-radius: 5px;
        box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
        margin-right: 10px;
        cursor: zoom-in;
    }

    p > img[alt="emoji"] {
        width: 22px;
        height: 22px;
        margin: 0 2px;
        box-shadow: none;
    }

    }
    }

    }

    pre {
        position: relative;

    &
    :hover {

    .code-copy {
        opacity: 1;
    }

    }

    .code-copy {
        position: absolute;
        right: 10px;
        top: 10px;
        opacity: 0;
        cursor: pointer;
        transition: all 0.3s;
    }

    }

    .slide_or_actions {
        width: 180px;
        position: absolute;
        right: 110px;
        transition: all 0.3s;

    .slider_bar {

        border-radius: 5px;
        box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
        background-color: var(--card_bg);
        overflow: hidden;

    .title {
        padding: 10px;
        display: flex;
        justify-content: center;
        align-items: center;

    span {
        margin-right: 10px;
    }

    }

    .body {
        background-color: var(--card_bg);
        padding: 10px 20px 20px 20px;

    p {
        width: 100%;
        height: 30px;
        line-height: 30px;
        cursor: pointer;
        transition: all 0.3s;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        color: var(--font_1);

    &
    :hover {
        background-color: rgba(0, 0, 0, 0.1);
    }

    }

    p[tagname='H1'] {
    }

    p[tagname='H2'] {
      padding-left: 10px;
    }

    p[tagname='H3'] {
      padding-left: 15px;
    }

    p[tagname='H4'] {
      padding-left: 20px;
    }

    p[tagname='H5'] {
      padding-left: 25px;
    }

    p[tagname='H6'] {
      padding-left: 30px;
    }

    }
    }

    .article_actions {
        margin-top: 20px;
        display: flex;
        flex-direction: column;
        align-items: center;

    .item {
        width: 60px;
        height: 60px;
        border-radius: 50%;
        background-color: var(--card_bg);
        margin-bottom: 20px;
        box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        font-size: 13px;

    i {
        font-size: 23px;
        cursor: pointer;
        color: var(--font_1);
    }

    i.show {
        color: var(--active);
    }

    }
    }

    }


    .slide_or_actions.show {
        width: 250px;

    &
    ~ .article {
        width: calc(100% - 270px);
    }

    .title {
        border-bottom: 1px solid var(--bg);
    }

    .body {
    }

    }

    .slide_or_actions.fixed {
        position: fixed;
        top: 80px;
    }


    .markdown-body.editormd-html-preview {

    ul {
        list-style: initial;

    li {
        line-height: 1.8rem;
        list-style: initial;
    }

    }

    p {
        margin-top: 5px;
        margin-bottom: 5px;
    }

    }

    .el-scrollbar__wrap {
        overflow-x: hidden !important;
    }


</style>

{# index.js #}
<script>
    axios.interceptors.request.use(request => {
        if (request.method !== 'GET') {
            let csrftoken = document.querySelector('input[name="csrfmiddlewaretoken"]').value
            request.headers['X-CSRFToken'] = csrftoken
        }
        return request
    })
    axios.interceptors.response.use(response => {
        return response.data
    })


    /*
    function dynamic_navigation() {
        let a_list = document.querySelectorAll('#dynamic_nav>a')
        let path = location.pathname
        for (const a of a_list) {
            let a_href = a.getAttribute('href')
            if (a_href === path || a_href + '/' === path) {
                a.classList.add('active')
            }
        }
    }

    dynamic_navigation()
 */

    function getDisTop(element) {   //获取元素距离页面顶部的距离
        let realTop = element.offsetTop;
        let parent = element.offsetParent;
        while (parent !== null) {
            realTop += parent.offsetTop;
            parent = parent.offsetParent;
        }
        return realTop;
    }

    function setCookie(name, value) {
        let exp = new Date();
        exp.setTime(exp.getTime() + 2000);
        document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString();
    }

    //获取cookie
    function getCookie(name) {
        var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
        if (arr = document.cookie.match(reg))
            return unescape(arr[2]);
        else
            return null;
    }

    var vue = new Vue({
        el: "#app",
        delimiters: ["[[", "]]"],
        data: {
            // 弹窗宽度
            max_dialog_width: '50%',
            min_dialog_width: '30%',
            theme: 'light', //默认主题
            //分类
            this_category: 'qianduan',
            comment_content: '', //评论内容,

            isShowSlider: false,
            slide_list: [],
            slide_text: '显示悬浮目录', //显示悬浮目录

            // 手机适配显示导航栏
            nav_drawer: false,

            search_key: '',

            news_list: [],  // 新闻列表

            news_init: [
                {
                    name: '微博',
                    subtitle: '热搜榜',
                    id: 'KqndgxeLl9',
                    url: '/static/my/img/news/weibo.png'
                },
                {
                    name: '抖音',
                    subtitle: '热门视频榜',
                    id: 'DpQvNABoNE',
                    url: '/static/my/img/news/douyin.png'
                },
                {name: 'CSDN论坛', id: 'K7GdajgeQy', url: 'http://cdn.qiniu.daoyuanyi.com/blog/news_logo/CSDN.png'},
                {name: '掘金', id: 'QaqeEaVe9R', url: 'http://cdn.qiniu.daoyuanyi.com/blog/news_logo/juejin.png'},
                {name: '吾爱破解', id: 'NKGoRAzel6', url: 'http://cdn.qiniu.daoyuanyi.com/blog/news_logo/wuaipojie.png'},
                {
                    name: '知乎',
                    subtitle: '热榜',
                    id: 'mproPpoq6O',
                    url: '/static/my/img/news/zhihu.png'
                },
                {
                    name: '哔哩哔哩',
                    subtitle: '全站日榜',
                    id: '74KvxwokxM',
                    url: '/static/my/img/news/bilibili.png'
                },
                {
                    name: '微信',
                    subtitle: '24h热文榜',
                    id: 'WnBe01o371',
                    url: '/static/my/img/news/weixin.png'
                },
                {
                    name: '百度',
                    subtitle: '实时热点',
                    id: 'Jb0vmloB1G',
                    url: '/static/my/img/news/baidu.png'
                },
                {name: '百度贴吧', id: 'Om4ejxvxEN', url: 'http://cdn.qiniu.daoyuanyi.com/blog/news_logo/baidutieba.png'},
                {
                    name: '36氪',
                    subtitle: '24小时热榜',
                    id: 'Q1Vd5Ko85R',
                    url: '/static/my/img/news/36ker.png'
                },
                {
                    name: '拼多多',
                    subtitle: '实时热销榜',
                    id: 'ARe1QZ2e7n',
                    url: '/static/my/img/news/pingduoduo.png'
                }
            ],
            news_active: '微博',
            news_active_url: '/static/my/img/news/weibo.png',
            sub_name: [],

            mood_dialogVisible: false,
            mood_add: {
                name: '',
                avatar_id: null,
                content: '',
                drawing: '',
            },

            mood_show_drawing: [],

            mood_comment_dialogVisible: false,

            mood_add_comment: {
                name: '',
                content: '',
            },

            history_dialogVisible: false,
            history: {
                title: '',
                create_date: new Date(),
                content: '',
                drawing: '',
            },
            history_edit_add: false,  // 默认是添加, 编辑是nid
            history_show_drawing: [],
            // 设置禁用状态，参数为当前日期
            history_pickerOptions: {
                disabledDate(time) {
                    return time.getTime() > Date.now();
                }
            },
            site_title: {
                title: ''
            },
            // 弹窗
            site_dialogVisible: false,
            site_add_edit_tag: false, //编辑添加
            site_tab_tag: '推荐',
            site_list: [],
            site_add_dialogVisible: false,
            site: {
                title: '',
                abstract: '',
                href: '',
                icon_href: '',
                tag: [],
            },
            site_add_edit: false,
            site_order: 'create_date', // 排序

            friends_links_dialog: false,

            feedback: {
                email: '',
                content: '',
            },

            article_pwd: '',
            edit_cover_dialog: false,
            edit_cover: {
                nid: '',  // 图片id
                aid: '',  // 文章id
            },

            project_dialog: false,
            project: {
                title: '',
                article: [],
            },
            project_add_edit: false,
        },
        created() {
            this.init_dialog_width()
            this.init_theme()

            let path = location.pathname
            if (path.indexOf('article') !== -1) {
                this.init_slider()
            }
            if (path.indexOf('search') !== -1) {
                this.init_search_key()
            }
            if (path.indexOf('news') !== -1) {
                this.news_init_method(0)
            }
            if (path === '/') {
                this.news_init_method(1)
            }
            if (path.indexOf('sites') !== -1) {
                this.init_site()
            }

            // 异步函数需要延迟
            setTimeout(() => {
                this.get_sidebar()
                this.code_copy()
            }, 200)
        },
        mounted() {
            this.keyDown()
            let path = location.pathname
            if (path.indexOf('search') === -1) {
                setTimeout(() => {
                    this.init_scrollbar()
                }, 100)

            }
        },
        methods: {
            // 初始化弹窗大小
            init_dialog_width() {
                let w = $(document).width()
                if (w > 850) {

                } else if (w > 550) {
                    this.max_dialog_width = '70%'
                    this.min_dialog_width = '50%'
                } else if (w > 400) {
                    this.max_dialog_width = '90%'
                    this.min_dialog_width = '70%'
                } else {
                    this.max_dialog_width = '100%'
                    this.min_dialog_width = '90%'
                }
            },
            //初始化主题
            init_theme() {
                //读取存储的主题信息
                let theme = localStorage.getItem('theme')
                if (theme) {
                    this.theme = theme
                }
            },
            //设置主题
            setTheme(themeName) {
                this.theme = themeName
                localStorage.setItem('theme', themeName)
            },
            nav_open() {
                $('nav, .my_header,main,footer').addClass('open')
            },
            nav_close() {
                $('nav, .my_header,main,footer').removeClass('open')
            },

            // 图片加载失败
            img_error(e) {
                e.target.style.display = 'none'
            },
            // 监听方向键
            keyDown() {
                // 监听键盘
                let el_bar = document.querySelector('.el-scrollbar__wrap')
                document.onkeydown = (e) => {
                    //事件对象兼容
                    let e1 = e || event || window.event || arguments.callee.caller.arguments[0]
                    if (e1.target.classList.contains('viewer-open')) {
                        return
                    }

                    let top = el_bar.scrollTop  // 获取现在的位置
                    if (e1.code === 'ArrowDown') {  // 下
                        $(el_bar).animate({scrollTop: top + 20}, 0)
                    } else if (e1.code === 'ArrowUp') { // 上
                        $(el_bar).animate({scrollTop: top - 20}, 0)
                    }
                }
            },
            // 滚动条初始化
            init_scrollbar() {
                let bar = this.$refs.scrollbar.wrap
                let slider = document.querySelector('.slide_or_actions')
                let nav = document.querySelector('.nav_bg')
                let top1 = 0;
                let path = location.pathname
                let old_url = localStorage.getItem('current_url')
                let new_url = location.href
                if (path.indexOf('article') !== -1 || path.indexOf('about') !== -1) {
                    top1 = $(slider).offset().top - 80
                }
                if (old_url === new_url) {
                    // 刷新
                    let top = localStorage.getItem('current_top')
                    localStorage.setItem('current_top', '0')
                    let el_bar = document.querySelector('.el-scrollbar__wrap')
                    $(el_bar).animate({scrollTop: top}, 0)
                }

                bar.onscroll = () => {
                    let top = bar.scrollTop

                    if (top >= 200) {
                        nav.classList.add('show')
                    } else {
                        nav.classList.remove('show')
                    }
                    if (slider) {
                        if (top >= top1) {
                            slider.classList.add('fixed')
                        } else {
                            slider.classList.remove('fixed')
                        }
                    }
                }
            },

            //切换分类
            switch_article_category(categoryName) {
                this.this_category = categoryName
            },

            // 发布评论
            add_comment(nid) {
                let content = AnalyticMarkDown(this.comment_content)
                axios.post(`/api/article/comment/${nid}/`, {content}).then(res => {
                    // 校验不成功
                    if (res.code) {
                        if (res.self) {
                            this.$refs[`comment_${res.self}`].focus()
                        }
                        this.$message.error(res.msg)
                        return
                    }
                    this.$message.success(res.msg)
                    setTimeout(() => {
                        location.reload()
                    }, 500)
                })
            },
            // 将被评论人的用户名写到placeholder
            set_sub_placeholder(div, username, cid) {
                $(div).find('textarea').attr('placeholder', `@${username}`)
                {#$(div).find('textarea')[0].focus()#}
                $(div).find('textarea').attr('cid', cid)
            },
            // 展示子评论列表
            show_sub_comment_list(e, username, cid) {
                let div = $(e.target).parent().parent().next()
                $(div).slideToggle()
                this.set_sub_placeholder(div, username, cid)
            },
            // 子评论回复显示
            sub_comment_set_placeholder(e, username, cid) {
                let div = $(e.target).parents('.sub_comment_list')
                this.set_sub_placeholder(div, username, cid)
            },
            // 发布子评论
            add_sub_comment(e, nid) {
                // nid 文章id
                // cid  评论id
                axios.post(`/api/article/comment/${nid}/`, {
                    content: $(e.target).prev().val(),
                    pid: $(e.target).prev().attr('cid')
                }).then(res => {
                    if (res.code) {
                        if (res.self) {
                            this.$refs[`sub_comment_${res.self}`].focus()
                        }
                        this.$message.error(res.msg)
                        return
                    }
                    this.$message.success(res.msg)
                    setTimeout(() => {
                        location.reload()
                    }, 500)
                })
            },
            // 删除子评论
            delete_sub_comment(nid, aid, root_comment_id) {
                this.$confirm('此操作将永久删除该评论, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    axios.delete(`/api/article/comment/${nid}/`, {
                        data: {
                            aid,
                            pid: root_comment_id
                        }
                    }).then(res => {
                        if (res.code) {
                            this.$message.error(res.msg)
                            return
                        }
                        this.$message.success(res.msg)
                        setTimeout(() => {
                            location.reload()
                        }, 500)
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '取消删除'
                    });
                });
            },

            // 评论点赞
            comment_digg(e, nid) {
                axios.post(`/api/comment/digg/${nid}/`).then(res => {
                    if (res.code) {
                        this.$message.error(res.msg)
                        return
                    }
                    e.target.innerHTML = `点赞 (${res.data})`
                    this.$message.success(res.msg)
                })
            },
            // 文章点赞
            article_digg(e, nid) {
                let dom = e.target
                dom.classList.add('show')

                axios.post(`/api/article/digg/${nid}/`).then(res => {
                    if (res.code) {
                        this.$message.error(res.msg)
                        return
                    }
                    $(dom).next().text(res.data)
                    this.$message.success(res.msg)
                })

                let timer = null
                timer = setTimeout(() => {
                    clearTimeout(timer)
                    dom.classList.remove('show')
                }, 1000)
            },
            // 文章收藏
            article_collects(e, nid) {
                let dom = e.target
                axios.post(`/api/article/collects/${nid}/`).then(res => {
                    if (res.code) {
                        this.$message.error(res.msg)
                        return
                    }
                    this.$message.success(res.msg)
                    $(dom).next().text(res.data)
                    if (res.isCollects) {
                        dom.classList.add('show')
                        return;
                    }
                    dom.classList.remove('show')
                })
            },

            // 回到顶部
            go_to_top() {
                let bar = this.$refs.scrollbar.wrap
                $(bar).animate({
                    scrollTop: 0
                }, 500)
            },

            // 初始化
            init_slider() {
                let flag = localStorage.getItem('isShowSlider')
                setTimeout(() => {
                    let box = document.querySelectorAll('.el-scrollbar__view')[1]
                    let height = box.offsetHeight
                    if (height > 500) {
                        height = 500
                    } else if (height === 0) {
                        height = 200
                    }
                    document.getElementById('el_scrollbar').style.height = height + 'px'
                }, 300)
                if (flag) {
                    flag = eval(flag)
                    this.isShowSlider = flag
                    this.$nextTick(() => {
                        this.sliderChange(flag)
                    })
                } else {
                    this.isShowSlider = false
                    this.$nextTick(() => {
                        this.sliderChange(false)
                    })
                }
            },
            // 悬浮目录是否显示
            sliderChange(val) {
                {#let dom = this.$refs.slider#}
                {#localStorage.setItem('isShowSlider', val)#}
                {#if (val) {#}
                {#    dom.classList.add('show')#}
                {#    this.slide_text = '关闭悬浮目录'#}
                {#    return#}
                {# }#}
                {#dom.classList.remove('show')#}
                {#this.slide_text = '打卡悬浮目录'#}

                let dom = this.$refs.slider
                localStorage.setItem('isShowSlider', val)
                if (val) {
                    dom.classList.add('show')
                    this.side_text = '关闭悬浮目录'
                    $(dom).find('.body').slideDown()
                    return
                }
                this.side_text = '开启悬浮目录'
                $(dom).find('.body').slideUp()
                dom.classList.remove('show')
            },
            // 悬浮目录
            get_sidebar() {
                let content = $('#article_content')
                let h_List = content.children('h1, h2, h3, h4, h5, h6')
                let lis = []
                for (let i = 0; i < h_List.length; i++) {
                    let c = h_List[i].innerText
                    let tagName = h_List[i].tagName
                    let tagId = h_List[i].id
                    let ele = {
                        tagName,
                        c,
                        pos: '#' + tagId
                    }
                    lis.push(ele)
                }

                lis.push({
                    tagName: 'H1',
                    c: '去评论吧!',
                    pos: '.comment_submit'
                })
                this.slide_list = lis
            },
            // 去目录指定位置
            go_side_bar(selector, e) {
                $('.slider_bar .body p').css('color', '')
                let bar = this.$refs.scrollbar.wrap

                e.target.style.color = '#ff9800'
                let top = getDisTop($(selector)[0])
                $(bar).animate({scrollTop: top - 80}, 600)
            },

            // 代码一键复制
            code_copy() {
                $('pre').each(function () {
                    let copy = $('<i title="copy" class="el-icon-document-copy code-copy"></i>')
                    $(this).append(copy)
                })
                $('pre i.code-copy').click(e => {
                    let text_list = $(e.target).prev().find('code')
                    let text = ''
                    text_list.each(function () {
                        text += $(this).text() + '\n';
                    })
                    let element = $('<textarea>' + text + '</textarea>')
                    $('body').append(element)
                    element[0].select()
                    document.execCommand('Copy')
                    element.remove()

                    // 复制成功的提示信息
                    this.$message.success('复制成功')
                })
            },

            // 点击搜索
            search(path = '/search/', target = '_blank') {
                let box = document.querySelector('.search')
                if (!box.classList.contains('show_search')) {
                    // 搜索框展开
                    box.classList.add('show_search')
                    box.querySelector('input').focus()
                    return;
                }
                if (!this.search_key) {
                    box.classList.remove('show_search')
                    return;
                }
                // 打开标签页
                window.open(path + '?key=' + this.search_key, name = target)
            },
            // 初始化搜索词
            init_search_key() {
                let dom = document.querySelector('.search_key_input')
                let key = dom.getAttribute('data')
                this.search_key = key
            },

            // 获取热搜数据
            get_new_data(id, name, url, flag, size) {
                if (name === this.news_active && !flag) {
                    return
                }
                this.news_active = name
                this.news_active_url = url

                let data = {
                    id,
                }
                if (size) {
                    data.size = size
                }

                let headers = this.news_headers

                axios.post('/api/news/', data, {headers}).then(res => {
                    this.news_list = res.data
                })
            },
            // 初始化新闻，获取加密头
            news_init_method(size) {
                setTimeout(() => {
                    let e = new Date;
                    e.toUTCString();
                    const t = e.getTime().toString();
                    let signaturekey = $.OM.AES.encrypt(t, "itab1314").toString()
                    this.news_headers = {
                        signaturekey,
                    }
                    this.get_new_data('KqndgxeLl9', '微博', '/static/my/img/news/weibo.png', true, size)
                }, 100)

                {#this.sub_name = this.news_init.map((item, i) => {#}
                {#    return item.subtitle#}
                {# })#}
                {#console.log(this.sub_name)#}
            },

            mood_show_comment_list(e) {
                let div = $(e.target).parent().parent().next()
                $(div).slideToggle()
            },
            // 发布心情
            mood_add_method() {
                axios.post('/api/moods/', this.mood_add).then(res => {
                    if (res.code) {
                        this.$message.error(res.msg)
                        this.$refs[`mood_add__${res.self}`].focus()
                        return
                    }
                    this.$message.success(res.msg)
                    setTimeout(() => {
                        location.reload()
                    }, 1000)
                })
            },
            // 删除心情
            mood_delete(nid, e) {
                this.$confirm('此操作将永久删除该心情, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    axios.delete(`/api/moods/${nid}/`).then(res => {
                        if (res.code) {
                            this.$message.error(res.msg)
                            return
                        }
                        this.$message.success(res.msg)
                        setTimeout(() => {
                            $(e.target).parents('.mood').remove()
                        }, 500)
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            // 打开回复心情的对话框
            mood_comment_dialogVisible_show(nid) {
                this.mood_comment_dialogVisible = true
                this.mood_comment_add_method.nid = nid
            },
            // 心情评论
            mood_comment_add_method() {
                let nid = this.mood_comment_add_method.nid

                axios.post(`/api/mood_comments/${nid}/`, this.mood_add_comment).then(res => {
                    if (res.code) {
                        this.$message.error(res.msg)
                        this.$refs[`mood_comment_add__${res.self}`].focus()
                        return
                    }
                    this.$message.success(res.msg)
                    setTimeout(() => {
                        location.reload()
                    }, 1000)
                })
            },
            // 心情评论删除
            mood_sub_comment_delete(nid, mood_id, e) {
                this.$confirm('此操作将永久删除该评论, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    // nid是评论id，mood_id是心情id
                    axios.delete(`/api/mood_comments/${nid}/`, {
                        data: {
                            mood_id
                        }
                    }).then(res => {
                        if (res.code) {
                            this.$message.error(res.msg)
                            return
                        }
                        this.$message.success(res.msg)
                        setTimeout(() => {
                            $(e.target).parents('.mood').find('.mood_comment_num').text(`评论（${res.data}}）`)
                            $(e.target).parents('li').remove()
                        }, 300)
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            // 心情点赞和心情评论点赞
            mood_digg(path, nid, e) {
                axios.put(`/api/${path}/${nid}/`).then(res => {
                    if (res.code) {
                        this.$message.error(res.msg)
                        return
                    }
                    this.$message.success(res.msg)
                    $(e.target).text(`点赞（${res.data}}）`)
                })
            },

            // 回忆录
            uploadImgFromPaste(file) {
                axios.post('/api/paste_upload/', {image: file}).then(res => {
                    this.history.drawing += res.url + '\n'
                })
            },
            history_add_edit_method(nid) {
                axios.post('/api/history/' + nid, this.history).then(res => {
                    if (res.code) {
                        this.$message.error(res.msg)
                        return
                    }
                    this.$message.success(res.msg)
                    this.history_dialogVisible = false
                    location.reload()
                })
            },
            history_add_method(nid) {
                if (!nid) {
                    // 添加事件
                    this.history_add_edit_method('')
                    return
                }
                // 编辑事件
                this.history_add_edit_method(nid + '/')
            },
            // 粘贴上传
            paste_upload(e) {
                let clipboardData = (e.clipboardData || e.originalEvent.clipboardData);
                let items = clipboardData.items, len = items.length, blob = null;


                //在items里找粘贴的image,据上面分析,需要循环
                for (let i = 0; i < len; i++) {
                    if (items[i].type.indexOf("image") !== -1) {
                        //getAsFile() 此方法只是living standard firefox ie11 并不支持
                        blob = items[i].getAsFile();
                    }
                }
                if (blob !== null) {
                    // 读取图片文件
                    let reader = new FileReader();
                    reader.onload = (event) => {
                        // event.target.result 即为图片的Base64编码字符串
                        let base64_str = event.target.result
                        //可以在这里写上传逻辑 直接将base64编码的字符串上传（可以尝试传入blob对象，看看后台程序能否解析）
                        this.uploadImgFromPaste(base64_str);
                    }
                    reader.readAsDataURL(blob);
                    //阻止默认行为即不让剪贴板内容在div中显示出来
                    // e.preventDefault();
                }

            },
            // 代码复用
            history_edit_show(e, nid, title, create_date) {
                this.history.title = title
                this.history.create_date = create_date
                let div = e.target
                this.history_edit_add = nid
                this.history.content = div.getAttribute('content')
                this.history.drawing = div.getAttribute('drawing')
                this.history_dialogVisible = true
            },
            // 回忆录删除
            history_remove(nid, e) {
                this.$confirm('此操作将永久删除该事件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    // nid是评论id，mood_id是心情id
                    axios.delete(`/api/history/${nid}/`).then(res => {
                        if (res.code) {
                            this.$message.error(res.msg)
                            return
                        }
                        $(e.target).parents('.timeline-item').remove()
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            history_handleClose(done) {
                this.$confirm('关闭之后，修改的数据失效，确认关闭？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                    .then(() => {
                        this.history.title = ''
                        this.history.create_date = new Date()
                        this.history_edit_add = false
                        this.history.content = ''
                        this.history.drawing = ''
                        done();
                    })
                    .catch(() => {
                    });
            },


            // 添加/编辑标签方法
            site_add_edit_tag_method(nid) {
                axios.post('/api/site_tag/' + nid, this.site_title).then(res => {
                    if (res.code) {
                        this.$message.error(res.msg)
                        return
                    }
                    this.$message.success(res.msg)
                    location.reload()
                })
            },
            site_add_tag(nid) {
                if (!nid) {
                    // 添加
                    this.site_add_edit_tag_method('')
                    return
                } else {
                    // 编辑
                    this.site_add_edit_tag_method(nid + '/')
                }
            },
            // 编辑展示
            site_tag_edit_show(nid, title) {
                this.site_add_edit_tag = nid
                this.site_title.title = title
                this.site_dialogVisible = true
            },
            site_tag_handleClose(done) {
                this.site_add_edit_tag = false
                this.site_title.title = ''
                done()
            },
            site_tag_remove(e, nid) {
                this.$confirm('此操作将永久删除该标签, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    // nid是评论id，mood_id是心情id
                    axios.delete(`/api/site_tag/${nid}/`).then(res => {
                        if (res.code) {
                            this.$message.error(res.msg)
                            return
                        }
                        $(e.target).remove()
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            // 标签切换显示
            site_tag_tab_show(title) {
                this.site_tab_tag = title

                this.site_get_list(title, this.site_order)
            },
            site_get_list(title, order) {
                axios.get('/api/sites/', {
                    params: {
                        title,
                        order
                    }
                }).then(res => {
                    this.site_list = res
                })
            },

            init_site() {
                this.site_get_list(this.site_tab_tag, this.site_order)
            },
            // 添加/编辑方法
            site_add(nid) {
                console.log(nid)
                if (!nid) {
                    axios.post('/api/sites/', this.site).then(res => {
                        if (res.code) {
                            this.$message.error(res.msg)
                            $(`#site_add__${res.self}`)[0].focus()
                            return
                        }
                        this.$message.success(res.msg)
                        this.site_add_dialogVisible = false
                        this.init_site()
                    })
                } else {
                    axios.put(`/api/sites/${nid}/`, this.site).then(res => {
                        if (res.code) {
                            this.$message.error(res.msg)
                            $(`#site_add__${res.self}`)[0].focus()
                            return
                        }
                        this.$message.success(res.msg)
                        this.site_add_dialogVisible = false
                        this.init_site()
                    })
                }

                this.site = {
                    title: '',
                    abstract: '',
                    href: '',
                    icon_href: '',
                    tag: [],
                }
            },
            // 编辑展示
            site_edit_show(item) {
                let tag = []
                // 列表字典[{},...] 快捷键：forof
                for (const itemElement of item.tags) {
                    tag.push(itemElement.nid)
                }
                this.site = {
                    title: item.title,
                    abstract: item.abstract,
                    href: item.href,
                    icon_href: item.icon_href,
                    tag
                }
                this.site_add_edit = item.nid
                this.site_add_dialogVisible = true
            },
            // 编辑退出清除
            site_edit_close(done) {
                done()
                this.site_add_edit = false
                this.site = {
                    title: '',
                    abstract: '',
                    href: '',
                    icon_href: '',
                    tag: [],
                }
            },
            // 删除
            site_remove(e, nid) {
                this.$confirm('此操作将永久删除该网站, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    // nid是评论id，mood_id是心情id
                    axios.delete(`/api/sites/${nid}/`).then(res => {
                        if (res.code) {
                            this.$message.error(res.msg)
                            return
                        }
                        $(e.target).parent().parent().remove()
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            // 站点顺序
            site_order_method(order) {
                this.site_order = order
                this.site_get_list(this.site_tab_tag, this.site_order)
            },
            // 点赞
            site_digg(e, item) {
                axios.post(`/api/site_digg/${item.nid}/`).then(res => {
                    if (res.code) {
                        this.$message.error(res.msg)
                        return
                    }
                    this.$message.success(res.msg)
                    item.digg_count += 1
                    $(e.target).parent().parent().addClass('show')

                    setTimeout(() => {
                        $(e.target).parent().parent().removeClass('show')
                    }, 2000)
                })
            },
            // 收藏
            site_coll(e, item) {
                axios.post(`/api/site_coll/${item.nid}/`).then(res => {
                    if (res.code) {
                        this.$message.error(res.msg)
                        return
                    }
                    this.$message.success(res.msg)
                    if (res.data === 1) {
                        $(e.target).parent().parent().addClass('show')
                    } else {
                        $(e.target).parent().parent().removeClass('show')
                    }
                    item.collects_count += res.data
                })
            },
            // 友情链接
            friend_link_add() {
                axios.post('/api/friends_links/', this.site).then(res => {
                    if (res.code) {
                        this.$message.error(res.msg)
                        $(`#site_add__${res.self}`)[0].focus()
                        return
                    }
                    this.$message.success(res.msg)
                    this.friends_links_dialog = false
                })
            },
            // 意见反馈
            feedback_add() {
                axios.post('/api/feedback/', this.feedback).then(res => {
                    if (res.code) {
                        this.$message.error(res.msg)
                        $(`#feedback__${res.self}`)[0].focus()
                        return
                    }
                    this.$message.success(res.msg)
                    this.feedback.content = ''
                })
            },
            // 查看加密文章
            article_pwd_show(nid) {
                axios.post(`/api/article_pwd/${nid}/`, {pwd: this.article_pwd}).then(res => {
                    if (res.code) {
                        this.$message.error(res.msg)
                        document.querySelector('#article_pwd').focus()
                        return
                    }
                    this.$message.success(res.msg)
                    location.reload()
                })
            },


            show_edit_cover(aid, nid) {
                this.edit_cover.aid = aid
                this.edit_cover.nid = nid
                this.edit_cover_dialog = true
            },
            // 修改文章封面
            edit_cover_method(aid) {
                // aid 文章的id
                let nid = this.edit_cover.nid  // 新的图片id
                axios.post(`/api/article/cover/${aid}/`, {nid}).then(res => {
                    location.reload()
                })
            },

            to_bilibili() {
                window.open('https://space.bilibili.com/482546956')
            },
            call_me() {
                this.$message.warning('该功能暂未开通')
            },
        },
        watch: {
            'mood_add.drawing'(n, o) {
                this.mood_show_drawing = n.split('\n')
            },
            'history.drawing'(n, o) {
                this.history_show_drawing = n.split('\n')
            },
        }
    })


    let w = true;  // 点击a标签的跳转就回到顶部
    $('a').click(e => {
        w = false
    })
    window.onbeforeunload = e => {
        // 将滚动条的位置和当前url写入
        if (w) {
            let el_bar = document.querySelector('.el-scrollbar__wrap')
            let url = location.href
            localStorage.setItem('current_top', el_bar.scrollTop)  // 离开前 距离页面顶部的高度
            localStorage.setItem('current_url', url)  // 离开前的的网站路径
        }
    };


</script>